package com.zprmb.udzt;

import java.text.DecimalFormat;

import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.zprmb.udzt.util.Constant;
import com.zprmb.udzt.util.LogUtils;
import com.zprmb.udzt.util.ToastUtil;
import com.zprmb.udzt.util.VolleryUtil;

/**
 * 转出
 * @author shenshao
 */

public class DexterityPayOutActivity extends BaseActivity implements OnClickListener{

	private ImageView iv_v4_dexterity_out_back;
	private ImageView img_nowork;
	private TextView tv_v4_dexterity_out_title;
	private int countByToday;//当天转出的总次数
	private double repayRate;//费率
	private TextView tv_v4_dexterity_pay_out_chiyou;
	private TextView tv_v4_dexterity_pay_out_zhuanchu;
	private TextView tv_v4_dexterity_pay_out_zhuanchuup;
	private TextView tv_v4_dexterity_pay_out_shouxu;
	private TextView tv_v4_dexterity_pay_out_daozhang;
    private TextView tv_dexterity_pay_out_tishi0;
	private TextView tv_dexterity_pay_out_tishi1;
	private TextView tv_dexterity_pay_out_tishi2;
	private EditText et_v4_dexterity_pay_out_jine;
	private TextView tv_v4_dexterity_pay_out_up;
	DecimalFormat df = new DecimalFormat("###0.00");  
	DecimalFormat df2 = new DecimalFormat("###0");  
	private double currentAmount,ying_daozhang;//持有金额
	private int redemptionMaxAmount;//单笔上限
	private RelativeLayout rl_back,rl_activity;
	private TextView tv_desc,tv_up_money;
	private ScrollView sv;
	private Double transferableAmount;
	private String url,desc="";
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.v4_dexterity_pay_out_activity);
		 BbtApplication.getInstance().addActvity(this);
		initView();
	}
	
	protected void onResume() {
		super.onResume();
		et_v4_dexterity_pay_out_jine.setText("");
		initData();
	}
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		BbtApplication.getInstance().removeActvity(this);
	}
	private void initData() {
		VolleryUtil vollery = new VolleryUtil() {
			
			@Override
			public void onUpDate(JSONObject jsonObject) {
				// TODO Auto-generated method stub
				if (jsonObject.optInt("success")==1) {
					LogUtils.e("转出", jsonObject.toString());
					sv.setVisibility(View.VISIBLE);
					img_nowork.setVisibility(View.GONE);
					JSONObject json = jsonObject.optJSONObject("data");
					JSONObject json1=json.optJSONObject("activityDesc");
					transferableAmount=json.optDouble("transferableAmount");
					tv_v4_dexterity_pay_out_chiyou.setText(json.optString("currentAmount")+"元");
					currentAmount = json.optDouble("currentAmount");
					tv_v4_dexterity_pay_out_zhuanchu.setText(df.format(transferableAmount)+"元");
					if(json1!=null){						
						url=json1.optString("url");
						desc=json1.optString("desc");
						tv_desc.setText(json1.optString("desc"));
					}
				    if(desc.length()<=0){
						rl_activity.setVisibility(View.GONE);
					}else{
						rl_activity.setVisibility(View.VISIBLE);
					}
                     
					tv_v4_dexterity_pay_out_zhuanchuup.setText("(转出单笔限额"+df2.format(Double.parseDouble(json.optString("redemptionMaxAmount"))/10000)+"万元,单日限额"+df2.format(Double.parseDouble(json.optString("redemptionMaxAmountDay"))/10000)+"万)");
					redemptionMaxAmount = json.optInt("redemptionMaxAmount");
					tv_dexterity_pay_out_tishi0.setText("1.智投宝当日转入的金额当日不可转出,次日后可正常转出");
					tv_dexterity_pay_out_tishi1.setText("2.单笔转出限额"+df2.format(json.optDouble("redemptionMaxAmount")/10000)+"万元,"+"单日转出限额"+df2.format(json.optDouble("redemptionMaxAmountDay")/10000)+"万元");
					tv_dexterity_pay_out_tishi2.setText("3.每天第一笔转出免费，之后每笔转出手续费是转出金额的"+json.optJSONObject("currentInfo").optDouble("repayRate")*10+"‰，如不足1元按1元计费");
				    
					countByToday = json.optInt("countByToday");
					
					repayRate = json.optJSONObject("currentInfo").optDouble("repayRate");
					
				}else {
					if (jsonObject.optString("comment").equals("please login")) {
						Intent intent = new Intent(DexterityPayOutActivity.this,LoginActivity.class);
						startActivity(intent);
						DexterityPayOutActivity.this.finish();
					}
					
				}
			}
			
			@Override
			public void onError() {
				// TODO Auto-generated method stub
				sv.setVisibility(View.GONE);
				img_nowork.setVisibility(View.VISIBLE);
				Toast.makeText(DexterityPayOutActivity.this, "请求失败   请检查网络设置", 2000).show();
			}
		};
		vollery.setHeaders("token", getToken());
		vollery.setHeaders("client", "android");
		
		vollery.setRequestMethod(1);
		vollery.execute(this, Constant.URL+"api/v2/claim/fund/current/out","");
	}

	private void initView() {
		iv_v4_dexterity_out_back = (ImageView) findViewById(R.id.img_back);
		img_nowork=(ImageView)findViewById(R.id.iv_v4_nonetwork);
		tv_up_money=(TextView)findViewById(R.id.up_money);
		iv_v4_dexterity_out_back.setOnClickListener(this);
		tv_v4_dexterity_out_title = (TextView) findViewById(R.id.tv_v4_dexterity_out_title);
		tv_v4_dexterity_out_title.getPaint().setFakeBoldText(true);
		tv_v4_dexterity_out_title.setText("智投宝转出");
		sv=(ScrollView)findViewById(R.id.sv);
		rl_activity=(RelativeLayout)findViewById(R.id.rl_activity);
		tv_desc=(TextView)findViewById(R.id.tv_desc);
		tv_dexterity_pay_out_tishi0=(TextView)findViewById(R.id.tv_dexterity_pay_out_tishi0);
		tv_v4_dexterity_pay_out_chiyou = (TextView) findViewById(R.id.tv_v4_dexterity_pay_out_chiyou);
		tv_v4_dexterity_pay_out_zhuanchu = (TextView) findViewById(R.id.tv_v4_dexterity_pay_out_zhaunchu);
		tv_v4_dexterity_pay_out_zhuanchuup = (TextView) findViewById(R.id.tv_v4_dexterity_pay_out_zhaunchuup);
		tv_v4_dexterity_pay_out_shouxu = (TextView) findViewById(R.id.tv_v4_dexterity_pay_out_shouxu);
		tv_v4_dexterity_pay_out_daozhang = (TextView) findViewById(R.id.tv_v4_dexterity_pay_out_daozhang);
		tv_dexterity_pay_out_tishi1 = (TextView) findViewById(R.id.tv_dexterity_pay_out_tishi1);
		tv_dexterity_pay_out_tishi2 = (TextView) findViewById(R.id.tv_dexterity_pay_out_tishi2);
		et_v4_dexterity_pay_out_jine = (EditText) findViewById(R.id.et_v4_dexterity_pay_out_jine);
		tv_v4_dexterity_pay_out_up = (TextView) findViewById(R.id.tv_v4_dexterity_pay_out_up);
		rl_back=(RelativeLayout)findViewById(R.id.rl_back);
		tv_up_money.setOnClickListener(this);
		rl_back.setOnClickListener(this);
		rl_activity.setOnClickListener(this);
		sv.setVisibility(View.GONE);
		tv_v4_dexterity_pay_out_up.setOnClickListener(this);
		et_v4_dexterity_pay_out_jine.addTextChangedListener(new TextWatcher() {
			public void onTextChanged(CharSequence s, int arg1, int arg2, int arg3) {
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                        s = s.toString().subSequence(0,
                                s.toString().indexOf(".") + 3);
                        et_v4_dexterity_pay_out_jine.setText(s);
                        et_v4_dexterity_pay_out_jine.setSelection(s.length());
                    }
                }
                if (s.toString().trim().substring(0).equals(".")) {
                    s = "0" + s;
                    et_v4_dexterity_pay_out_jine.setText(s);
                    et_v4_dexterity_pay_out_jine.setSelection(2);
                }
 
                if (s.toString().startsWith("0")
                        && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                    	et_v4_dexterity_pay_out_jine.setText(s.subSequence(0, 1));
                    	et_v4_dexterity_pay_out_jine.setSelection(1);
                        return;
                    }
                }
			}
			public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
			}
			public void afterTextChanged(Editable arg0) {
				if (!arg0.toString().equals("")) {
					if (countByToday==0) {
						tv_v4_dexterity_pay_out_shouxu.setText("0.00元");
						tv_v4_dexterity_pay_out_daozhang.setText(arg0.toString()+"元");
						ying_daozhang=Double.valueOf(arg0.toString());
					}else {
						DecimalFormat df = new DecimalFormat("######0.00");
						try {
							double a =Double.valueOf(arg0.toString());
							double b = a*repayRate/100d;
							
							if (Double.valueOf(et_v4_dexterity_pay_out_jine.getText().toString())>1) {
								if (b<1) {
									b = 1.00;
								}
								double c = a-b;
								if (c<0) {
									c = 0;
									
								}
								
									
								
								tv_v4_dexterity_pay_out_shouxu.setText(df.format(b)+"元");
								tv_v4_dexterity_pay_out_daozhang.setText(df.format(c)+"元");
								ying_daozhang=c;
							}else {
								tv_v4_dexterity_pay_out_shouxu.setText(et_v4_dexterity_pay_out_jine.getText().toString()+"元");
								tv_v4_dexterity_pay_out_daozhang.setText("0.00元");
							}
						} catch (NumberFormatException e) {
							e.printStackTrace();
							tv_v4_dexterity_pay_out_shouxu.setText("0.00元");
							tv_v4_dexterity_pay_out_daozhang.setText("0.00元");
						}
					}
				} else {
					tv_v4_dexterity_pay_out_shouxu.setText("0.00元");
					tv_v4_dexterity_pay_out_daozhang.setText("0.00元");
				}
			}
		});
	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.img_back:
			finish();
			break;
		case R.id.rl_back:
			finish();
			break;
		case R.id.rl_activity:
			
				Intent intent=new Intent(DexterityPayOutActivity.this,V4WebViewActivity.class);
				intent.putExtra("url", url+"?app=true");
				intent.putExtra("title", desc);
				startActivity(intent);
				break;
		case R.id.tv_v4_dexterity_pay_out_up:
			try {
				if (Double.valueOf(et_v4_dexterity_pay_out_jine.getText().toString())>1) {
					
				}
			} catch (NumberFormatException e) {
				e.printStackTrace();
				ToastUtil.showCenterToast(this, "转出金额输入错误");
				return;
			}
			if (et_v4_dexterity_pay_out_jine.getText().toString().equals("")) {
				ToastUtil.showCenterToast(this, "请输入转出金额");
				return;
			}
			if (transferableAmount==0) {
				ToastUtil.showCenterToast(this, "今日可转出金额不足");
				return;
			}
			if (Double.valueOf(et_v4_dexterity_pay_out_jine.getText().toString())>transferableAmount) {
				ToastUtil.showCenterToast(this, "转出金额不能大于今日可转出金额");
				return;
			}
//			if (Double.valueOf(et_v4_dexterity_pay_out_jine.getText().toString())>currentAmount) {
//				ToastUtil.showCenterToast(this, "持有金额不足");
//				return;
//			}
			if (Double.valueOf(et_v4_dexterity_pay_out_jine.getText().toString())>redemptionMaxAmount) {
//				ToastUtil.showCenterToast(this, "单笔转出上限为"+redemptionMaxAmount+"元");
				ToastUtil.showCenterToast(this, "转出金额不能大于单笔转出上限");
				return;
			}
			tv_v4_dexterity_pay_out_up.setEnabled(false);
			verityUser();
			break;
		case R.id.up_money:
			Intent intent3=new Intent(DexterityPayOutActivity.this,V4WebViewActivity.class);
	    	intent3.putExtra("url", "/h5/currCompareFixed?app=true");
	    	intent3.putExtra("title", "定期理财");
	    	
    	    startActivity(intent3);
			break;
		}
	}
	
	private void verityUser(){
		VolleryUtil vollery = new VolleryUtil() {
			
			@Override
			public void onUpDate(JSONObject jsonObject) {
				// TODO Auto-generated method stub
				if (jsonObject.optInt("success")==1) {
					JSONObject json = jsonObject.optJSONObject("data");
					Intent intent = null;
					if (!json.optBoolean("nameAuth")&&!json.optBoolean("isBindCard")) {
						intent = new Intent(DexterityPayOutActivity.this,BankCardActivity.class);
						startActivity(intent);
						return;
					}
//					if (!json.optBoolean("nameAuth")) {
//						intent = new Intent(DexterityPayOutActivity.this,VerityCardActivity.class);
//						startActivity(intent);
//						return;
//					}
					if (!json.optBoolean("isBindCard")) {
						intent = new Intent(DexterityPayOutActivity.this,BankCardActivity.class);
						startActivity(intent);
						return;
					}
					intent = new Intent(DexterityPayOutActivity.this,PayDexterityActivity.class);
					intent.putExtra("amount", et_v4_dexterity_pay_out_jine.getText().toString());
					intent.putExtra("actual", ying_daozhang);
					if (!json.optBoolean("payPass")) {
						intent.putExtra("setPass", 1);
					}
					intent.putExtra("type", "OUT");
					intent.putExtra("fee", tv_v4_dexterity_pay_out_shouxu.getText().toString());
					startActivity(intent);
					overridePendingTransition(R.anim.slide_in_from_bottom, R.anim.slide_out_to_bottom);
				}else {
					if (jsonObject.optString("comment").equals("please login")) {
						Intent intent = new Intent(DexterityPayOutActivity.this,LoginActivity.class);
						startActivity(intent);
					}else {
						ToastUtil.showCenterToast(DexterityPayOutActivity.this, jsonObject.optString("comment"));
					}
				}
				tv_v4_dexterity_pay_out_up.setEnabled(true);
			}
			
			@Override
			public void onError() {
				// TODO Auto-generated method stub
				tv_v4_dexterity_pay_out_up.setEnabled(true);
			}
		};
		vollery.setHeaders("token", DexterityPayOutActivity.this.getSharedPreferences("config", 0).getString("token", ""));
		vollery.setHeaders("client", "android");
		vollery.setShow(true);
		vollery.setRequestMethod(0);
		vollery.execute(DexterityPayOutActivity.this, Constant.URL+"apiAccount/userInfo", "");
	}
}
